<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/23
 * Time: 10:39
 * 总部
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\AgentChain;
use app\common\model\AgentOrder;
use app\common\model\AgentSendTips;
use app\common\model\AgentShipment;
use app\common\model\AgentShop;
use app\common\model\ChainFunds;
use app\common\model\Commission;
use app\common\service\UserService;
use think\Db;

class Warehouse extends Api {
	
	/**
	 * 统计
	 */
	public function statistics() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		$isAdmin = false;
		if($level != \app\admin\model\User::LEVEL_WAREHOUSE) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] != \app\admin\model\User::LEVEL_WAREHOUSE) {
				$this->error('权限不足');
			}
			$isAdmin = true;
			$userId = $adminLevel['user_id'];
		}
		
		$agentInfo = Db::name('agentShop')
			->where(['user_id' => $userId])
			->field('name, image, sale_number, order_number, sale_amount, id, status, chain_user_id')
			->find();
		if(!$agentInfo || $agentInfo['status'] == AgentShop::STATUS_D) {
			$this->error('当前身份已被禁用');
		}
		
		//粉丝
		$fans = UserService::getFansNumById($userId);
		
		//场景店
		$shop = Db::name('agentShop')->where([
			'role' => \app\admin\model\User::LEVEL_SHOP,
			'status' => AgentShop::STATUS_Y,
			'warehouse_id' => $agentInfo['id']
			])->count();
		
		//推广员
		$agents = Db::name('agentShop')
			->where(['warehouse_id' => $agentInfo['id'], 'status' => AgentShop::STATUS_Y])
			->column('user_id', 'id');
		$ids = array_values($agents);
		$ids[] = $userId;
		$promotion = Db::name('promotion')
			->where(['recommend_user_id' => ['in', $ids], 'status' => \app\common\model\Promotion::STATUS_Y])
			->count();
		
		//库存
		$stock = Db::name('agentStock')->where(['user_id' => $userId])->sum('number');
		
		//销售佣金
		$saleCommission = Db::name('commission')->where(['user_id' => $userId, 'type' => ['in', [Commission::TYPE_SALE, Commission::TYPE_RECOMMEND]]])->sum('amount');
		
		//提货佣金
		$goodsCommission = Db::name('commission')->where(['user_id' => $userId, 'type' => Commission::TYPE_GOODS])->sum('amount');
		$orderNumber = Db::name('agentShipment')->where(['sign_agent_id' => $agentInfo['id'], 'status' => AgentShipment::STATUS_WAIT])->count();
		
		//我的奖励数量
		$user = $this->auth->getUser();
		$selfNumber = $user['reward_number'];
		
		//提货点数量
		$warehouse = Db::name('agentShop')
			->where([
				'recommend_user_id' => $userId,
				'role' => \app\admin\model\User::LEVEL_WAREHOUSE,
				'status' => AgentShop::STATUS_Y
				])
			->count();
		
		$isChain = 0;
		if($agentInfo['chain_user_id']) {
			//连锁店的下级
			$isChain = 1;
			$count = Db::name('chainFunds')->where(['agent_id' => $agentInfo['id']])
				->group('type')
				->column('sum(amount) as amount', 'type');
			
			$promotionCommisson = $count[2] ?? 0;
			$selfCommission = $count[1] ?? 0;
			$goodsCommission = $count[3] ?? 0;
			
			$saleCommission = $promotionCommisson + $selfCommission;
		} else {
			//连锁店的管理者
			$chain = Db::name('agentChain')->where(['user_id' => $userId, 'status' => AgentChain::STATUS_NORMAL])->find();
			$chain && $isChain = 2;
		}
		
		//未发货提醒数量
		$sendNumber = Db::name('agentSendTips')->where(['user_id' => $this->auth->id, 'status' => AgentSendTips::STATUS_WAIT])
			->count();
		
		$this->success('查询成功', [
			'fans' => $fans,
			'order_number' => $agentInfo['order_number'],
			'sale_number' => $agentInfo['sale_number'],
			'order_amount' => $agentInfo['sale_amount'],
			'shop' => $shop,
			'stock_order_number' => $orderNumber,
			'promotion' => $promotion,
			'sale_commission' => $saleCommission,
			'goods_commission' => $goodsCommission,
			'stock' => $stock,
			'self_number' => $selfNumber,
			'warehouse' => $warehouse,
			'is_chain' => $isChain,
			'agentInfo' => $agentInfo,
			'send_number' => $sendNumber,
			'is_admin' => $isAdmin
		]);
	}
	
	/**
	 * 创建订单
	 */
	public function createOrder() {
		$userId = $this->auth->id;
		if($this->auth->level != \app\admin\model\User::LEVEL_USER) {
			$this->error('你已经有推广权限');
		}
		if($this->area == \app\admin\model\User::AREA_OTHER) {
			$setting = Db::name('setting')->find();
		} else {
			$setting = Db::name('ruleSz')->find();
		}
		if(!$setting || $setting['level_warehouse_amount'] <= 0) {
			$this->error('敬请开放加盟');
		}
		
		$rid = $this->request->post('rid');
		!$rid && $this->error('请通过分享加盟');
		
		$userModel = new \app\admin\model\User();
		$recommendUser = $userModel->find($rid);
		if(!$recommendUser || !in_array($recommendUser['level'],[$userModel::LEVEL_CENTER, $userModel::LEVEL_PROMOTION, $userModel::LEVEL_WAREHOUSE])) {
			$this->error('分享人没有该推荐权限');
		}
		
		
		$model = new AgentOrder();
		$row = $model->where(['user_id' => $userId])->find();
		if(!$row) {
			
			$res = $model->isUpdate(false)
				->save([
					'recommend_user_id' => $rid,
					'user_id' => $userId,
					'level' => \app\admin\model\User::LEVEL_WAREHOUSE,
					'amount' => $setting['level_warehouse_amount'],
				]);
			if(!$res) {
				$this->error('创建订单出错');
			}
			
			$id = $model->getLastInsID();
		} else {
			$res = $model->save(['amount' => $setting['level_warehouse_amount'], 'recommend_user_id' => $rid, 'level' => \app\admin\model\User::LEVEL_WAREHOUSE], ['id' => $row['id']]);
			if($res === false) {
				$this->error('创建订单出错');
			}
			$id = $row['id'];
		}
		
		$notifyUrl = $this->request->domain() . url('api/notify/promotion', '', false);
		$config = config('weixin');
		$obj = new \app\common\library\Weixin($config['smallapp']['app_id']);
		
		$user = \app\admin\model\User::get($userId);
		$data = $obj->unifiedOrder($id, $setting['level_warehouse_amount'],$notifyUrl, $user['smallapp_openid']);
		$this->success($data['msg'], $data['data'], $data['code']);
		
	}
	
	
	public function commission() {
		$userId = $this->auth->id;
		$agent = Db::name('agentShop')->where(['user_id' => $userId])->find();
		$where['agent_id'] = $agent['id'];
		
		$type = $this->request->post('type', 1, 'intval');
		$types = [ChainFunds::TYPE_DESTORY];
		if($type == 1) {
			$types = [ChainFunds::TYPE_SELF, ChainFunds::TYPE_SON];
		}
		$where['type'] = ['in', $types];
		
		$page = $this->request->post('page', 1, 'intval');
		$count = Db::name('chainFunds')->where($where)->count();
		$list = Db::name('chainFunds')->where($where)
			->page($page)
			->order(['create_time' => 'desc'])
			->field('id, from_unixtime(create_time, \'%y/%m/%d\') as date, amount, type')
			->select();
		
		if($list) {
			$typeList = ChainFunds::$typeList;
			foreach ($list as &$row) {
				$row['type_text'] = $typeList[$row['type']] ?? '';
			}
		}
		
		$this->success('查询成功', [
			'total' => $count,
			'list' => $list
		]);
	}
}
